import json
import logging
from enum import Enum

import requests

from api.serial import sample
from detecter import settings

logger = logging.getLogger('django')

if settings.IS_TEST:
    url = settings.TEST_SERVER_URL
else:
    url = settings.SERVER_URL

sample_send_url = f'{url}/sample/insert_sample'
temp_send_url = f'{url}/sample/insert_temperature'
# 平板操作
pad_url = f'{url}/pad/pad'
headers = {
    f"Content-Type": f"{settings.CONTENT_TYPE}"}

OK_CODE = 200
SUCCESS_CODE = 0


class UpdateType(Enum):
    ADD_GOOD = 2
    ADD_BAD = 3
    POS_FEEDBACK = 1  # 良品+1同时不良品-1
    NEG_FEEDBACK = -1  # 不良+1 同时良品-1


def update_product(update_type=UpdateType.ADD_GOOD, frame_length=None):
    product_url = None
    if update_type == UpdateType.ADD_GOOD:
        # product_url = f"{pad_url}/update/{settings.MACHINE_CODE}"
        product_url = f"{pad_url}/updateNew/{settings.MACHINE_CODE}/{frame_length}"

        # product_url = f"{pad_url}/dealAbnormalByMachine/{settings.MACHINE_CODE}"
    elif update_type == UpdateType.ADD_BAD:
        # product_url = f"{pad_url}/update_error/{settings.MACHINE_CODE}"
        product_url = f"{pad_url}/update_errorNew/{settings.MACHINE_CODE}/{frame_length}"
    elif update_type == UpdateType.POS_FEEDBACK:
        product_url = f"{pad_url}/update_count/{settings.MACHINE_CODE}/{update_type.value}"
    elif update_type == UpdateType.NEG_FEEDBACK:
        product_url = f"{pad_url}/update_count/{settings.MACHINE_CODE}/{update_type.value}"
    get(product_url, None)


def sample_send(sample_frame_list, mould_code):
    url = f'{sample_send_url}/{settings.MACHINE_CODE}/{mould_code}'
    frame_list = []
    index = 0
    # 降采样
    for frame in sample_frame_list:
        if index % 10 == 0:
            frame_list.append(frame)
        index += 1
    json_str = json.dumps(frame_list, ensure_ascii=False, cls=sample.NpEncoder)
    post(url, json_str)


def temp_send(temp_list, mould_code):
    url = f'{temp_send_url}/{settings.MACHINE_CODE}/{mould_code}'
    json_str = json.dumps(temp_list, ensure_ascii=False, cls=sample.NpEncoder)
    post(url, json_str)


def analyse_response(result):
    if result["code"] == SUCCESS_CODE:
        return result["data"]
    else:
        logger.error(result['msg'])


def get(url, data):
    try:
        response = requests.get(url, data, timeout=(3.05, 27))
        # response = requests.put(url, data, timeout=(3.05, 27))
        if response.status_code == OK_CODE:
            logger.info(f'{url}:{response.json()}')
            result = analyse_response(response.json())
            # by zxy on 20191114
            response.close()
            return result
        else:
            logger.error(f"{response},网络异常,无法成功访问接口")
    except Exception as e:
        logger.error(e)


def post(url, data):
    try:

        response = requests.post(url, data, headers=headers, timeout=(3.05, 27))
        if response.status_code == OK_CODE:
            logger.info(f'{url}:{response.json()}')
            result = analyse_response(response.json())
            # by zxy on 20191114
            response.close()
            return result
        else:
            logger.error(f"{response},网络异常,无法成功访问接口")
    except Exception as e:
        logger.error(e)
